<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                  <a-input
                    :disabled="formDisabled"
                    v-model="model.billNo"
                    placeholder="请输入单据编号"
                    disabled
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicationId">
                  <select-person-input :disabled="formDisabled" v-model="model.applicationId" @back="selectEmployee" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="填表时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    :disabled="formDisabled"
                    placeholder="请选择填表时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicant">
                  <j-select-depart
                    :disabled="formDisabled"
                    v-model="model.applicant"
                    placeholder="请选择申请单位"
                    disabled
                  />
                  <!-- <a-input :disabled="formDisabled" v-model="model.applicant" placeholder="请输入申请单位"></a-input> -->
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applicationDeptId">
                  <j-select-depart :disabled="formDisabled" v-model="model.applicationDeptId" disabled />
                  <!-- <a-input :disabled="formDisabled" v-model="model.applicationDeptId" placeholder="请输入申请单位"></a-input> -->
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input :disabled="formDisabled" v-model="model.teamId" :tdlx="3" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="编制人数"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="staffingQuantity"
                >
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.staffingQuantity"
                    placeholder="请输入编制人数"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="实际人数"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="practicalQuantity"
                >
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.practicalQuantity"
                    placeholder="请输入实际人数"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="所需人数"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="requireQuantity"
                >
                  <a-input-number
                    :disabled="formDisabled"
                    :max="99999999"
                    :min="0"
                    v-model="model.requireQuantity"
                    placeholder="请输入所需人数"
                    style="width: 100%"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="增岗事由" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="requireReason">
                  <j-dict-select-tag :disabled=formDisabled type="list" v-model="model.requireReason" dictCode="require_reason" placeholder="请选择增岗事由" />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea
                    :disabled="formDisabled"
                    v-model="model.remark"
                    rows="4"
                    placeholder="请输入备注"
                    :max-length="500"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="岗位明细">
            <a-row>
              <a-col :span="24">
                <div style="margin-bottom: 6px; margin-top: 6px">
                  <a-button @click="handleAdd" v-if="!formDisabled" type="primary">新增</a-button>
                </div>
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="id"
                  :loading="loading"
                  :columns="columns"
                  :pagination="false"
                  :data-source="model.itemList"
                  :scroll="{ x: true }"
                >
                  <span slot="action" slot-scope="text, record">
                    <template v-if="!formDisabled">
                      <a-button
                        class="ruleButton"
                        :ghost="true"
                        type="primary"
                        icon="edit"
                        @click="handleEdit(record)"
                      />
                      <a-divider type="vertical" />
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                        <a-button class="ruleButton" :ghost="true" type="primary" icon="delete" />
                      </a-popconfirm>
                    </template>
                  </span>
                </a-table>
              </a-col>
              <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
                <a-button @click="submitForm">提 交</a-button>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachments">
                  <j-upload :disabled="formDisabled" v-model="model.attachments"></j-upload>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <erp-hr-post-requirement-item-modal ref="itemList" @ok="modalFormOk"></erp-hr-post-requirement-item-modal>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import moment from 'moment'
import { mapGetters } from 'vuex'
import { validateDuplicateValue } from '@/utils/util'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import SelectPersonInput from '@/views/scy/components/SelectPersonInput'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import ErpHrPostRequirementItemModal from '../ErpHrPostRequirementItemModal'

export default {
  name: 'ErpHrPostRequirementBillForm',
  components: {
    SelectPersonInput,
    SelectTeamInput,
    SelectCustomerInput,
    SelectProjectInput,
    ErpHrPostRequirementItemModal
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false,
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false,
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      activeKey: ['1', '2', '3'],
      model: {
        itemList: [],
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
      },
      confirmLoading: false,
      validatorRules: {
        applicationId: [
            { required: true, message: '请选择申请人!'},
        ],
        teamId: [
            { required: true, message: '请选择申请团队!'},
        ],
        staffingQuantity: [
            { required: true, message: '请输入编制人数!'},
        ],
        practicalQuantity: [
            { required: true, message: '请输入实际人数!'},
        ],
        requireQuantity: [
            { required: true, message: '请输入所需人数!'},
        ],
      },
      url: {
        getBillNo: '/api/erp/hr/post/erpHrPostRequirementBill/getBillNo',
        add: '/api/erp/hr/post/erpHrPostRequirementBill/add',
        edit: '/api/erp/hr/post/erpHrPostRequirementBill/edit',
        queryById: '/api/erp/hr/post/erpHrPostRequirementBill/queryById',
        queryEmployeeById: '/api/erp/files/employee/erpEmployeeFile/queryPageById',
      },
      loading: false,
      dictOptions: {},
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '岗位名称',
          align: 'center',
          dataIndex: 'postId',
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['postId'], text + '')
            }
          },
        },
        {
          title: '工作地点',
          align: 'center',
          dataIndex: 'workAddress',
          // customRender: (text) => {
          //   if (!text) {
          //     return ''
          //   } else {
          //     return filterMultiDictText(this.dictOptions['workAddress'], text + '')
          //   }
          // },
        },
        {
          title: '所需人数',
          align: 'center',
          dataIndex: 'requireQuantity',
        },
        {
          title: '学历要求',
          align: 'center',
          dataIndex: 'educationalRequirements',
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['educationalRequirements'], text + '')
            }
          },
        },
        {
          title: '性别要求',
          align: 'center',
          dataIndex: 'sexRequirements',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['sexRequirements'], text + '')
            }
          },
        },
        {
          title: '专业要求',
          align: 'center',
          dataIndex: 'professionalRequirement',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['professionalRequirement'], text + '')
            }
          },
        },
        {
          title: '工作经验',
          align: 'center',
          dataIndex: 'workExperience',
          customRender: (text) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['workExperience'], text + '')
            }
          },
        },
        {
          title: '薪资区间（元）',
          align: 'center',
          dataIndex: 'salarySection',
        },
        {
          title: '期待到岗时间',
          align: 'center',
          dataIndex: 'expectationTime',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action',
          },
        },
      ],
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    },
  },
  watch: {
    activeKey(key) {
      this.$forceUpdate()
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
    //加载数据字典信息
    this.initDictConfig()
  },
  methods: {
    //获取编号
    getBillNo() {
      let that = this
      getAction(this.url.getBillNo, {}).then((res) => {
        if (res.success) {
          let data = res.result.records || res.result
          this.$set(this.model, 'billNo', data)
        }
      })
    },
    ...mapGetters(['userInfo']),
    add() {
      this.$set(this.modelDefault,"itemList",[]);
      this.edit(this.modelDefault);
      this.getBillNo();
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    },
    edit(record) {
      this.$refs.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
    },
    selectEmployee(data){
      getAction(this.url.queryEmployeeById,{ id: data[0].id }).then(res => {
        console.log(res);
        if(res.success){
          let data=res.result.records[0];
          this.$set(this.model,'applicant',data.orgDepart);
          this.$set(this.model,'applicationDeptId',data.departmentId);
          this.$set(this.model,'teamId',data.teamId);
         
        }
      })
    },
    //加载数据字典信息
    initDictConfig() {
      initDictOptions('sys_position,name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'postId', res.result)
        }
      })
      // initDictOptions('sys_depart,name,id').then((res) => {
      //   if (res.success) {
      //     this.$set(this.dictOptions, 'workAddress', res.result)
      //   }
      // })
      initDictOptions('educational_requirements').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'educationalRequirements', res.result)
        }
      })
      initDictOptions('sex_requirements').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'sexRequirements', res.result)
        }
      })
      initDictOptions('professional_requirement').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'professionalRequirement', res.result)
        }
      })
      initDictOptions('work_experience').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'workExperience', res.result)
        }
      })
    },
    //子表新增
    handleAdd() {
      this.$refs.itemList.add()
      this.$refs.itemList.title = '新增'
      this.$refs.itemList.disableSubmit = false
    },
    //子表编辑
    handleEdit(record) {
      this.$refs.itemList.edit(record)
      this.$refs.itemList.title = '修改'
      this.$refs.itemList.disableSubmit = false
    },
    //子表删除
    handleDelete(id) {
      for (let i = 0; i < this.model.itemList.length; i++) {
        if (this.model.itemList[i].id == id) {
          this.model.itemList.splice(i, 1)
        }
      }
    },
    modalFormOk(data) {
      this.loading = true
      let flag = true
      // debugger;
      for (let i = 0; i < this.model.itemList.length; i++) {
        if (this.model.itemList[i].id == data.id) {
          this.model.itemList.splice(i, 1, data)
          flag = false
        }
      }
      if (flag) {
        this.model.itemList.push(data)
      }
      //设置所需人数
      let requireQuantity=0;
      if(this.model.itemList){
        this.model.itemList.forEach(item=>{
          if(item.requireQuantity){
            requireQuantity+=item.requireQuantity;
          }
        })
        this.$set(this.model,"requireQuantity",requireQuantity)
      }
      
      this.loading = false
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
                that.$emit('unButtonDisable');
              }
            }).catch(()=>{
              that.$emit('unButtonDisable');
            })
            .finally(() => {
              that.confirmLoading = false;
            })
          } else {
            that.$emit('unButtonDisable');
          }

        })
      },
  },
}
</script>
